<?php
require_once( 'Logger.php');
require_once( 'iface/IDataMapper.php');
require_once( 'iface/IDataExtractor.php');

class Model{
	protected  $conn;
	protected $logger;

	function __construct(){
		$this->logger = new Logger();
	}

	public function CloseDBConnection()
	{
		$this->conn->close();
	}
	
	protected function getConnection() {
		require_once('DbConnector.php');
		$db = Db::getInstance();
		try {
			$conn = $db->getConnection();
			return $conn;
		} catch( Exception $exception ) {
			return null;
			$this->logger->addLog($exception->getMessage(),ERROR_LEVEL);
		}
	}

	protected function formatParam($param)
	{
		if( is_numeric($param) ) {
			return $param;
		}

		if( $param=='' ) {
			return 'null';
		}
		return mysqli_real_escape_string($this->conn, $this->strip_mq_gpc($param));
	}
	
	protected function format($sql,$parameterArray) {
		if( is_array($parameterArray) ) {
			foreach($parameterArray as $k => $v) {
				$parameterArray[$k] = $this->formatParam($parameterArray[$k]);
			}
			return vsprintf($sql, $parameterArray);
		}

		return sprintf($sql, $this->formatParam($parameterArray));
	}

	private function strip_mq_gpc($arg) {
		if (get_magic_quotes_gpc()) {
			return stripslashes($arg);
		}
		return $arg;
	}
	
	
	protected function execute($query, $dataParser = "") {
		$result = mysqli_query($this->conn, $query);
		if (is_bool($result) === true) // will work for insert, update, delete
			return $result;
		else if(is_a($dataParser, IDataMapper)) {
			$resultList = array();
			while($row = mysqli_fetch_assoc($result)) {
				$resultList[] = $dataParser->mapRow($row);
			}
 			mysqli_free_result($result);
 			return $resultList;
		}
		else if(is_a($dataParser, IDataExtracor)) {
			$retval = $dataParser->extract($result);
 			mysqli_free_result($result);
			return $retval;			
		}
		else {
			//TODO:: some error should be thrown
		}
	}
}
?>